package com.zr.controller;

import com.zr.enums.CoreExceptionEnum;
import com.zr.exception.ServiceException;
import com.zr.utils.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public abstract class BaseController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    protected <T> T readJsonBody(HttpServletRequest request, Class<T> tClass) {

        T t = null;
        try {
            StringBuilder sb = new StringBuilder();
            InputStream inputStream = request.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String jsonStr;
            while ((jsonStr = bufferedReader.readLine()) != null) {
                sb.append(jsonStr);
            }
            jsonStr = sb.toString();

            logger.info("json数据：{}", jsonStr);
            t = JsonUtils.toBean(jsonStr, tClass);
        } catch (IOException e) {
            logger.info("读取httpServletRequest异常:{}", e);
            throw new ServiceException(CoreExceptionEnum.REQUEST_DATA_ERROR);
        }
        return t;
    }
}
